import { ref } from 'vue';

/**
 * 防抖
 * @param {Function} callback 函数
 * @param {number} delay 时间 ms
 * @return {Function} 回调
*/
export function useDebounce(callback, delay) {
  const timer = ref(null);

  function debounce(...args) {
    if (timer.value) {
      clearTimeout(timer.value);
    }
    timer.value = setTimeout(() => {
      callback(...args);
      timer.value = null;
    }, delay);
  }

  return debounce;
}

/**
 * 节流
 * @param {Function} fn  函数
 * @param {number} 时间 ms
 * @return {Function} 回调
*/
export function useThrottle(fn, delay) {
  const throttled = ref(false);
  
  return function(...args) {
    if (!throttled.value) {
      throttled.value = true;
      fn(...args);
      setTimeout(() => {
        throttled.value = false;
      }, delay);
    }
  };
}